package v1

import (
	"dolphin/sports/pkg/setting"
	"dolphin/sports/pkg/util"
	"strings"

	"github.com/ddliu/go-httpclient"
	"github.com/gin-gonic/gin"
)

type WebhookInfo struct {
	Msgtype string                 `json:"msgtype"`
	Text    map[string]interface{} `json:"text"`
}

func CheckAppID(c *gin.Context) {

	var dinginfo WebhookInfo
	text_content := make(map[string]interface{})
	dinginfo.Msgtype = "text"

	appId := c.Param("appid")
	values := []string{"/eureka/apps", appId}
	path := strings.Join(values, "/")
	EurekaUrl := setting.EurekaServer + path

	res, _ := httpclient.Get(EurekaUrl)

	if res != nil {
		defer res.Body.Close()
	}

	if res.StatusCode != 200 {
		text_content["content"] = "[系统异常] Eureka调用异常，请人工介入检查"
		dinginfo.Text = text_content
		httpclient.PostJson(setting.DingDingWebhook, dinginfo)
		return
	}

	realip := util.ReadIp(appId)
	if len(realip) == 0 {
		text_content["content"] = "[配置错误] 未找到" + appId + "的ip"
		dinginfo.Text = text_content
		httpclient.PostJson(setting.DingDingWebhook, dinginfo)
		return
	}

	health_url := "http://" + realip + ":8081/info"
	check_res, _ := httpclient.Get(health_url)

	if check_res.StatusCode == 200 {
		text_content["content"] = "[运行中] " + appId + "接口：" + health_url + " 有返回，默认启动成功，请开始测试"
		dinginfo.Text = text_content
		httpclient.PostJson(setting.DingDingWebhook, dinginfo)
		return
	}

	text_content["content"] = "[未运行] " + appId + "接口：" + health_url + " 没有返回，默认未启动，请稍后重试"
	dinginfo.Text = text_content
	httpclient.PostJson(setting.DingDingWebhook, dinginfo)
	return
}
